﻿Imports System.CodeDom
Imports System.Reflection
Imports System.CodeDom.Compiler
Imports System.IO
Public Class FormGen
    Const TEMPLATE_X_DESIGNER As String = "xLib_Template_FRM_1g.Designer.vb"
    Const TEMPLATE_XX_DESIGNER As String = "xLib_Template_FRM.Designer.vb"
    Const TEMPLATE_X_SRCCODE As String = "xLib_Template_FRM_1g.vb"
    Const TEMPLATE_XX_SRCCODE As String = "xLib_Template_FRM.vb"
    Const TEMPLATE_X_MANRES As String = "xLib_Template_FRM_1g.resx"
    Const TEMPLATE_XX_MANRES As String = "xLib_Template_FRM.resx"

    Const FORMEXTENSION As String = ".Designer.vb"
    Const MAN_RES_EXTENSION As String = ".resx"
    Const SRC_CODE_EXTENSION As String = ".vb"
    Dim pathSave As String
    Dim pathAllTemplates As String
    Dim unit As String
    Public dat As Dat


    ''' <summary>
    ''' konstruktor 
    ''' </summary>
    ''' <param name="path_templates">cesta k adresu s templetami </param>
    ''' <param name="path_save">cesta kde sa ulozia formjlarovske subory(formular)</param>
    ''' <param name="unit">nazvo unitu pre ktory ideme vytvarat formular</param>
    ''' <param name="pa_dat">dataset</param>
    ''' <remarks></remarks>
    Public Sub New(ByVal path_templates As String, ByVal path_save As String, ByVal unit As String, ByVal pa_dat As Dat)
        Me.pathSave = path_save
        Me.pathAllTemplates = path_templates
        Me.unit = unit
        Me.dat = pa_dat
    End Sub


    Private Function getFriendBoxTmpl(ByVal type As String, ByVal name As String) As String
        Dim code As String
        Dim fso, inputFile
        fso = CreateObject("Scripting.FileSystemObject")
        Try
            inputFile = fso.OpenTextFile(pathAllTemplates + "\ComponentTemplates\friendTpl.vb.tpl", 1)
            code = inputFile.ReadAll
        Catch ex As Exception
            Throw New Exception("CHYBA - Template pre friend časť sa nenašiel. " + vbCrLf + ex.Message, ex)
        End Try
        code = Replace(code, "{name}", name)
        code = Replace(code, "{type}", type)
        Return code
    End Function
    Private Function getTextBoxTmpl(ByVal tabIndex As Integer, ByVal name As String, ByVal p_x As Integer, ByVal p_y As Integer) As String
        Dim code As String
        Dim fso, inputFile

        fso = CreateObject("Scripting.FileSystemObject")
        Try
            inputFile = fso.OpenTextFile(pathAllTemplates + "\ComponentTemplates\textBoxTpl.vb.tpl", 1)
            code = inputFile.ReadAll
        Catch ex As Exception
            Throw New Exception("CHYBA - Template pre TextBox sa nenašiel. " + vbCrLf + ex.Message, ex)
        End Try
        code = Replace(code, "{nameTextBox}", name)
        code = Replace(code, "{point_x}", p_x)
        code = Replace(code, "{point_y}", p_y)
        code = Replace(code, "{tabIndex}", tabIndex)
        code = Replace(code, "{nameForm}", "Form1")   'meno formulara pouzite na viacerych miestach! nezabudnut
        Return code
    End Function
    Private Function getLabelTmpl(ByVal tabIndex As Integer, ByVal name As String, ByVal text As String, ByVal p_x As Integer, ByVal p_y As Integer) As String
        Dim code As String
        Dim fso, inputFile
        fso = CreateObject("Scripting.FileSystemObject")
        Try
            inputFile = fso.OpenTextFile(pathAllTemplates + "\ComponentTemplates\labelTpl.vb.tpl", 1)
            code = inputFile.ReadAll
        Catch ex As Exception
            Throw New Exception("CHYBA - Template pre Label sa nenašiel. " + vbCrLf + ex.Message, ex)
        End Try
        code = Replace(code, "{name}", name)
        code = Replace(code, "{point_x}", p_x)
        code = Replace(code, "{point_y}", p_y)
        code = Replace(code, "{tabIndex}", tabIndex)
        code = Replace(code, "{text}", text)
        Return code
    End Function
    Private Function getButtonTmpl(ByVal tabIndex As Integer, ByVal name As String, ByVal text As String, ByVal p_x As Integer, ByVal p_y As Integer) As String
        Dim code As String
        Dim fso, inputFile
        fso = CreateObject("Scripting.FileSystemObject")
        Try
            inputFile = fso.OpenTextFile(pathAllTemplates + "\ComponentTemplates\buttonTpl.vb.tpl", 1)
            code = inputFile.ReadAll
        Catch ex As Exception
            Throw New Exception("CHYBA - Template pre Button sa nenašiel. " + vbCrLf + ex.Message, ex)
        End Try
        code = Replace(code, "{name}", name)
        code = Replace(code, "{point_x}", p_x)
        code = Replace(code, "{point_y}", p_y)
        code = Replace(code, "{tabIndex}", tabIndex)
        code = Replace(code, "{text}", text)
        Return code
    End Function
    Private Function getComboBoxTmpl(ByVal tabIndex As Integer, ByVal name As String, ByVal p_x As Integer, ByVal p_y As Integer) As String
        Dim code As String
        Dim fso, inputFile
        fso = CreateObject("Scripting.FileSystemObject")
        Try
            inputFile = fso.OpenTextFile(pathAllTemplates + "\ComponentTemplates\comboBoxTpl.vb.tpl", 1)
            code = inputFile.ReadAll
        Catch ex As Exception
            Throw New Exception("CHYBA - Template pre SuperComboBox sa nenašiel. " + vbCrLf + ex.Message, ex)
        End Try
        code = Replace(code, "{name}", name)
        code = Replace(code, "{point_x}", p_x)
        code = Replace(code, "{point_y}", p_y)
        code = Replace(code, "{tabIndex}", tabIndex)
        Return code
    End Function



    Public Function getTmpls(ByVal path As String) As List(Of String)
        Dim tmpls As List(Of String)
        Try
            'tmpls = Directory.GetFiles(path).ToList()
            tmpls = Directory.GetDirectories(path).ToList()
        Catch ex As Exception
            Throw New Exception("CHYBA - cesta s typmi formulárov sa nenašla. " & ex.Message, ex)
        End Try
        For index As Integer = 0 To tmpls.Count - 1
            tmpls(index) = tmpls(index).Substring(path.Length + 1, tmpls(index).Length - path.Length - 1)
        Next

        Return tmpls
    End Function
    ''' <summary>
    ''' vygeneruj 3 formularove subory
    ''' </summary>
    ''' <param name="tmplDir">adresar s druhom tempatov(standard,ciselniky)</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function generateFormular(ByVal tmplDir As String)
        ' nacitanie tempatu zo suboru
        Dim AllPath As String = ""       ' cela cesta
        Dim formCode As String = ""
        Dim formType As String = ""
        Dim fileFormName As String = ""
        Dim gridCount As Integer = getGridCount(unit)
        Dim oldFormName As String = ""
        If (gridCount = 0) Then
            formType = "xx"
        ElseIf (gridCount >= 1) Then
            formType = "x"    ' potom treba poriesit ak bude pocet gridov >1
        End If
        Dim formName As String = ""
        If (formType = "x") Then

            AllPath = pathAllTemplates + "\Templates\" + tmplDir + "\" + TEMPLATE_X_DESIGNER
            formCode = Me.readTemplate(AllPath)
            'fileFormName = Me.TEMPLATE_X_DESIGNER
            fileFormName = unit + "_x" + FORMEXTENSION
            formName = unit + "_x"    ' nazov formularu, aj nazov suboru formularu(bude sa tahat z DS)
            ' formCode = Replace(formCode, "{formName}", formName)

            oldFormName = TEMPLATE_X_DESIGNER.Remove(TEMPLATE_X_DESIGNER.Length - ".Designer.vb".Length, ".Designer.vb".Length)
            formCode = Replace(formCode, oldFormName, formName)
        ElseIf (formType = "xx") Then

            AllPath = pathAllTemplates + "\Templates\" + tmplDir + "\" + TEMPLATE_XX_DESIGNER
            formCode = Me.readTemplate(AllPath)
            'fileFormName = Me.TEMPLATE_XX_DESIGNER
            fileFormName = unit + "_xx" + FORMEXTENSION
            formName = unit + "_xx"    ' nazov formularu, aj nazov suboru formularu(bude sa tahat z DS)

            oldFormName = TEMPLATE_XX_DESIGNER.Remove(TEMPLATE_XX_DESIGNER.Length - ".Designer.vb".Length, ".Designer.vb".Length)
            formCode = Replace(formCode, oldFormName, formName)
        End If

        ' vytvaranie formularu z nacitaneho templatu
        ' Dim formName As String = "Form1"    ' nazov formularu, aj nazov suboru formularu(bude sa tahat z DS)

        'formCode = Replace(formCode, "{formName}", formName)


        ' teraz postupne prechadzat dataset a lepit inicializaciu a friendov
        '-------------------------------------------------------------------
        Dim str As String() = initComponents()

        formCode = Replace(formCode, "Me.ResumeLayout(False)", "Me.ResumeLayout(False)" & vbCrLf & str(0))

        formCode = Replace(formCode, "End Class", str(1) & vbCrLf & "End Class")

        ' ulozenie vygenerovaneho formularu
        createDirectory(formType, tmplDir, formName, oldFormName)

        AllPath = pathSave + "\" + unit + "\" + fileFormName
        Me.writeForm(AllPath, formCode)
        runVS()

        Return Nothing
    End Function


    Private Function readTemplate(ByVal path As String) As String
        Dim str As String
        Dim fso, inputFile

        fso = CreateObject("Scripting.FileSystemObject")
        Try
            inputFile = fso.OpenTextFile(path, 1)
            str = inputFile.ReadAll
            inputFile.Close()
        Catch ex As Exception

            Throw New Exception("CHYBA - Template pre formulár sa nenašiel. " + vbCrLf + ex.Message, ex)
        End Try
        Return str
    End Function
    Private Function writeForm(ByVal path As String, ByVal formCode As String)
        Dim outputFile, fso
        fso = CreateObject("Scripting.FileSystemObject")
        Try
            outputFile = fso.CreateTextFile(path, True)

            outputFile.Write(formCode)
            outputFile.Close()
        Catch ex As Exception
            Throw New Exception("CHYBA - Formular sa nedá uložiť. " + vbCrLf + ex.Message, ex)
        End Try

        Return Nothing
    End Function

    Private Function initComponents() As String()
        Dim component As String = "xTextBox"
        Dim componentCode As String
        Dim friendCode As String
        Dim initCodes() As String = New String() {"", ""}
        Dim index As Integer = 0

        componentCode = ""
        friendCode = ""

        Dim aModVersionDataRows() As DataRow = dat.DsAmod.Tables("_a_Version").Select("_a_VID = Max(_a_VID)")
        Dim unitColumns() As DataRow
        Dim _a_VID As Int32
        Dim pocetGridovVUnite As Int32 = 0
        Dim str As String = "_a_UnitName = '" + unit + "'"
        Dim str2 As String
        Dim tablesUnit() As DataRow = dat.DsAmod.Tables("_Tables").Select(str)

        _a_VID = aModVersionDataRows(0).Item("_a_VID")

        Console.WriteLine(_a_VID)
        For Each tblUnit As DataRow In tablesUnit
            If _a_VID = tblUnit("_a_VID") Then
                Console.WriteLine(tblUnit("TableName").ToString())
                str2 = "TableName = '" + tblUnit("TableName") + "'"
                unitColumns = dat.DsAmod.Tables("_a_Columns").Select("_a_VID = Max(_a_VID) and " + str2)
                For Each clmnUnit As DataRow In unitColumns

                    ' tuto bude generovanie
                    component = clmnUnit("_a_ComponentType")
                    componentCode = ""
                    friendCode = ""
                    If (component = kkComponentTypes.kkxTextBox) Then
                        index += 1
                        componentCode = Me.getTextBoxTmpl(index, clmnUnit("ColumnName") + "_" + index.ToString(), 110, 30 * index)
                        friendCode = Me.getFriendBoxTmpl("xTextBox", clmnUnit("ColumnName") + "_" + index.ToString())
                        ' pre label
                        componentCode += vbCrLf & Me.getLabelTmpl(index, "lbl" + clmnUnit("ColumnName") + "_" + index.ToString(), clmnUnit("ColumnName") + "_" + index.ToString(), 10, 30 * index)
                        friendCode += vbCrLf & Me.getFriendBoxTmpl("xLabel", "lbl" + clmnUnit("ColumnName") + "_" + index.ToString())

                    ElseIf (component = kkComponentTypes.kkxButton) Then
                        index += 1
                        componentCode = Me.getButtonTmpl(index, clmnUnit("ColumnName") + "_" + index.ToString(), clmnUnit("ColumnName") + "_" + index.ToString(), 110, 30 * index)
                        friendCode = Me.getFriendBoxTmpl("xButton", clmnUnit("ColumnName") + "_" + index.ToString())
                        ' pre label
                        componentCode += vbCrLf & Me.getLabelTmpl(index, "lbl" + clmnUnit("ColumnName") + "_" + index.ToString(), clmnUnit("ColumnName") + "_" + index.ToString(), 10, 30 * index)
                        friendCode += vbCrLf & Me.getFriendBoxTmpl("xLabel", "lbl" + clmnUnit("ColumnName") + "_" + index.ToString())

                    ElseIf (component = kkComponentTypes.kkxComboSuper) Then
                        index += 1
                        componentCode = Me.getComboBoxTmpl(index, clmnUnit("ColumnName") + "_" + index.ToString(), 110, 30 * index)
                        friendCode = Me.getFriendBoxTmpl("xComboSuper", clmnUnit("ColumnName") + "_" + index.ToString())
                        ' pre label
                        componentCode += vbCrLf & Me.getLabelTmpl(index, "lbl" + clmnUnit("ColumnName") + "_" + index.ToString(), clmnUnit("ColumnName") + "_" + index.ToString(), 10, 30 * index)
                        friendCode += vbCrLf & Me.getFriendBoxTmpl("xLabel", "lbl" + clmnUnit("ColumnName") + "_" + index.ToString())

                    End If

                    initCodes(0) += vbCrLf & componentCode & vbCrLf
                    initCodes(1) += vbCrLf & friendCode & vbCrLf

                Next

            End If
        Next

        ' Dim resultCode As String = componentCode & vbCrLf + _
        ' " End Sub " & vbCrLf + _
        ' friendCode
        Return initCodes

    End Function
    ' naplni kombobox menami adresarov(teda druhmi templatov-ciselnik, standard....)
    Public Function fillTmplsCmbBx() As List(Of String)

        Dim file As String = Me.pathAllTemplates + "\Templates"
        Dim tmpls As List(Of String)
        tmpls = Me.getTmpls(file)
        Return tmpls
    End Function
    Private Sub createDirectory(ByVal FormType As String, ByVal tmplDir As String, ByVal formName As String, ByVal oldFormName As String)
        Dim code As String
        Directory.CreateDirectory(Me.pathSave + "\" + unit)

        If (FormType = "x") Then
            If (System.IO.File.Exists(pathSave + "\" + unit + "\" + formName + SRC_CODE_EXTENSION)) Then
                System.IO.File.Delete(pathSave + "\" + unit + "\" + formName + SRC_CODE_EXTENSION)
            End If
            If (System.IO.File.Exists(pathSave + "\" + unit + "\" + formName + MAN_RES_EXTENSION)) Then
                System.IO.File.Delete(pathSave + "\" + unit + "\" + formName + MAN_RES_EXTENSION)
            End If
            code = Me.readTemplate(pathAllTemplates + "\Templates\" + tmplDir + "\" + TEMPLATE_X_SRCCODE)

            code = Replace(code, oldFormName, formName)
            Me.writeForm(pathSave + "\" + unit + "\" + formName + SRC_CODE_EXTENSION, code)

            code = Me.readTemplate(pathAllTemplates + "\Templates\" + tmplDir + "\" + TEMPLATE_X_MANRES)
            code = Replace(code, oldFormName, formName)
            Me.writeForm(pathSave + "\" + unit + "\" + formName + MAN_RES_EXTENSION, code)

        ElseIf (FormType = "xx") Then
            If (System.IO.File.Exists(pathSave + "\" + unit + "\" + formName + SRC_CODE_EXTENSION)) Then
                System.IO.File.Delete(pathSave + "\" + unit + "\" + formName + SRC_CODE_EXTENSION)
            End If
            If (System.IO.File.Exists(pathSave + "\" + unit + "\" + formName + MAN_RES_EXTENSION)) Then
                System.IO.File.Delete(pathSave + "\" + unit + "\" + formName + MAN_RES_EXTENSION)
            End If
            code = Me.readTemplate(pathAllTemplates + "\Templates\" + tmplDir + "\" + TEMPLATE_XX_SRCCODE)
            code = Replace(code, oldFormName, formName)
            Me.writeForm(pathSave + "\" + unit + "\" + formName + SRC_CODE_EXTENSION, code)

            code = Me.readTemplate(pathAllTemplates + "\Templates\" + tmplDir + "\" + TEMPLATE_XX_MANRES)
            code = Replace(code, oldFormName, formName)
            Me.writeForm(pathSave + "\" + unit + "\" + formName + MAN_RES_EXTENSION, code)
            'System.IO.File.Copy(pathAllTemplates + "\Templates\" + tmplDir + "\" + Me.TEMPLATE_XX_SRCCODE, pathSave + "\" + unit + "\" + formName + SRC_CODE_EXTENSION)
            'System.IO.File.Copy(pathAllTemplates + "\Templates\" + tmplDir + "\" + Me.TEMPLATE_XX_MANRES, pathSave + "\" + unit + "\" + formName + MAN_RES_EXTENSION)




        End If
    End Sub
    Private Sub runVS()
        'Shell("C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe e:\11\11.sln", 1)
    End Sub

    Public Sub generujForm(ByVal unitNameInput As String)
        Dim aModVersionDataRows() As DataRow = dat.DsAmod.Tables("_a_Version").Select("_a_VID = Max(_a_VID)")
        Dim _a_VID As Int32
        Dim pocetGridovVUnite As Int32 = 0
        Dim UnitName As String = ""
        _a_VID = aModVersionDataRows(0).Item("_a_VID")
        Console.WriteLine(_a_VID)
        For Each aModDataRow As DataRow In dat.DsAmod.Tables("_ModulStructure").Rows
            If _a_VID = aModDataRow("_a_VID") And UnitName = unitNameInput Then
                For Each aModDataRowColumns As DataRow In dat.DsAmod.Tables("_a_Columns").Rows
                    If aModDataRowColumns("_a_ComponentType") = kkComponentTypes.kkxGrid Then
                        pocetGridovVUnite = pocetGridovVUnite + 1
                    End If
                Next
            End If
        Next
        Select Case pocetGridovVUnite
            Case Is > 0
                'generuj xx-sovy
            Case Is = 0
                'generuj x-ovy
        End Select
    End Sub

    Public Function getGridCount(ByVal unitNameInput As String) As Integer
        Dim aModVersionDataRows() As DataRow = dat.DsAmod.Tables("_a_Version").Select("_a_VID = Max(_a_VID)")

        Dim unitColumns() As DataRow

        Dim _a_VID As Int32
        Dim pocetGridovVUnite As Int32 = 0
        Dim str As String = "_a_UnitName = '" + unitNameInput + "'"
        Dim str2 As String
        Dim tablesUnit() As DataRow = dat.DsAmod.Tables("_Tables").Select(str)

        _a_VID = aModVersionDataRows(0).Item("_a_VID")

        Console.WriteLine(_a_VID)
        For Each tblUnit As DataRow In tablesUnit
            If _a_VID = tblUnit("_a_VID") Then
                'Console.WriteLine(tblUnit("TableName").ToString())
                str2 = "TableName = '" + tblUnit("TableName") + "'"
                unitColumns = dat.DsAmod.Tables("_a_Columns").Select("_a_VID = Max(_a_VID) and " + str2)
                For Each clmnUnit As DataRow In unitColumns
                    'Console.WriteLine("-" + clmnUnit("ColumnName").ToString() + "   " + clmnUnit("_a_ComponentType").ToString())
                    If (clmnUnit("_a_ComponentType") = kkComponentTypes.kkxGrid) Then
                        pocetGridovVUnite += 1
                    End If
                Next

            End If
        Next
        Console.WriteLine(pocetGridovVUnite.ToString())
        Return pocetGridovVUnite
    End Function
    Public Function getFormType2(ByVal unitNameInput As String) As String
        Dim aModVersionDataRows() As DataRow = dat.DsAmod.Tables("_a_Version").Select("_a_VID = Max(_a_VID)")
        Dim unitColumns() As DataRow
        Dim _a_VID As Int32
        Dim pocetGridovVUnite As Int32 = 0
        Dim str As String = "_a_UnitName = '" + unitNameInput + "'"
        Dim str2 As String
        Dim tablesUnit() As DataRow = dat.DsAmod.Tables("_Tables").Select(str)

        _a_VID = aModVersionDataRows(0).Item("_a_VID")

        Console.WriteLine(_a_VID)
        For Each tblUnit As DataRow In tablesUnit
            If _a_VID = tblUnit("_a_VID") Then
                Console.WriteLine(tblUnit("TableName").ToString())
                str2 = "TableName = '" + tblUnit("TableName") + "'"
                unitColumns = dat.DsAmod.Tables("_a_Columns").Select("_a_VID = Max(_a_VID) and " + str2)
                For Each clmnUnit As DataRow In unitColumns
                    ' tuto bude generovanie
                Next

            End If
        Next
        Return ""

    End Function
End Class
